package com.tm.portal.web.control;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;

import com.tm.portal.util.StringUtils;

public class AbstractController
{
public static final String STATUS = "status";
	
	public static final String WARN = "warn";
	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	public static final String MESSAGE = "message";
	public static final String CONTENT = "content";
	
	/**
	 *  根据Map输出JSON
	 * @param jsonMap
	 * @return
	 */
	public String ajaxJson(Map<String,? extends Object> jsonMap)
	{
		JsonConfig config = new JsonConfig();
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		JSONObject jsonObject = JSONObject.fromObject(jsonMap, config);
		return jsonObject.toString();
	}
	
	/**
	 * 输出列表
	 * @param jsonList
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	public String ajaxJson(List<? extends Object> jsonList) throws UnsupportedEncodingException
	{
		JsonConfig config = new JsonConfig();
		config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

		JSONArray jsonArray = JSONArray.fromObject(jsonList, config);
		String str = jsonArray.toString();
		return str;
	}
	
	/**
	 *  输出JSON警告消息
	 * @param message
	 * @return
	 */
	public String ajaxJsonWarnMessage(String message)
	{
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, WARN);
		jsonMap.put(MESSAGE, StringUtils.escapeHtmlJson(message));
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return jsonObject.toString();
	}

	/**
	 *  输出JSON成功消息
	 * @param message
	 * @return
	 */
	public String ajaxJsonSuccessMessage(String message)
	{
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, StringUtils.escapeHtmlJson(message));
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return jsonObject.toString();
	}


	/**
	 *  输出JSON错误消息
	 * @param message
	 * @return
	 */
	public String ajaxJsonErrorMessage(String message)
	{
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, ERROR);
		jsonMap.put(MESSAGE, StringUtils.escapeHtmlJson(message));
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return jsonObject.toString();
	}
}
